package com.hi.hiparty.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hi.hiparty.entity.Party;
import com.hi.hiparty.entity.User;
import com.hi.hiparty.manager.PartyManager;
import com.hi.hiparty.manager.PartyResult;
import com.hi.hiparty.manager.UserManager;
import com.hi.hiparty.util.GsonUtil;
import com.hi.hiparty.util.JSONResponseHelper;
import com.hi.hiparty.util.TimeUtils;
import com.hi.hiparty.util.WebUtil;

@Controller
public class PartyController {

	private static final Log logger = LogFactory.getLog(PartyController.class);

	@Autowired
	private PartyManager partyManager;

	@Autowired
	private UserManager userManager;

	@RequestMapping(value = "/mobileapi/party/publish")
	public void publish(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject result = new JSONObject();
		String title = WebUtil.getStringPara(request, "title", null);
		String description = WebUtil.getStringPara(request, "description", null);
		Date startTime = WebUtil.getDateValue(request, WebUtil.dateFormat, "starttime", null);
		Date endTime = WebUtil.getDateValue(request, WebUtil.dateFormat, "endtime", null);
		String address = WebUtil.getStringPara(request, "address", null);
		String province = WebUtil.getStringPara(request, "province", null);
		String city = WebUtil.getStringPara(request, "city", null);
		String area = WebUtil.getStringPara(request, "area", null);
		String partypos = WebUtil.getStringPara(request, "partypos", null);

		Integer userid = WebUtil.getIntPara(request, "userid");
		String userpos = WebUtil.getStringPara(request, "userpos", null);
		int memberSexLimit = WebUtil.getIntPara(request, "member_sex_limit", 0);

		User user = userManager.getUser(userid);
		if (null == user) {
			result.put("success", 0);
			result.put("error", "无法找到对应的用户");
			JSONResponseHelper.sendJSONResult(response, result, null);
			return;
		}

		logger.info("发布活动，用户ID[" + userid + "], 地点[" + address + "], title:[" + title + "]");

		Party party = new Party();
		party.setTitle(title);
		party.setDescription(description);
		party.setUserid(userid);
		party.setNickname(user.getNickname());
		party.setAvatarUrl(user.getAvatarUrl());
		party.setCreatorSex(user.getGender());
		party.setMemberSexLimit(memberSexLimit);
		party.setUserPos(userpos);
		party.setAddress(address);
		party.setProvince(province);
		party.setCity(city);
		party.setArea(area);
		party.setPartyPos(partypos);
		party.setStartTime(startTime);
		party.setEndTime(endTime);
		party.setCreateTime(new Date());

		logger.info(title + description + userid + userpos + address + partypos + startTime + endTime);

		PartyResult rs = partyManager.publishParty(party);

		if (rs.isSuccess()) {
			logger.info("发布活动成功，用户ID[" + userid + "], 地点[" + address + "], title:[" + title + "]");
			result.put("success", 1);
		} else {
			result.put("success", 0);
			// 是否针对db和solr来处理
			if (rs.getErrorCode() == PartyResult.ERROR_DB_EXCEPTION) {
				logger.error("error_db_exception." + rs.getErrorMsg());
			}
			if (rs.getErrorCode() == PartyResult.ERROR_SOLR) {
				logger.error("error_solr_exception." + rs.getErrorMsg());
			}
		}
		JSONResponseHelper.sendJSONResult(response, result, null);
	}

	@RequestMapping(value = "/mobileapi/party/update")
	public void update(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject result = new JSONObject();
		// des、userid、theme、address、tags、startTime、endTime、gender、partyType
		String description = WebUtil.getStringPara(request, "description", null);
		Long id = WebUtil.getLongPara(request, "userid", 0L);
		Integer userid = WebUtil.getIntPara(request, "userid");
		String address = WebUtil.getStringPara(request, "address", null);
		Date startTime = WebUtil.getDateValue(request, WebUtil.dateFormat, "startTime", null);
		Date endTime = WebUtil.getDateValue(request, WebUtil.dateFormat, "endTime", null);
		Integer gender = WebUtil.getIntPara(request, "gender", 0);
		Integer partyType = WebUtil.getIntPara(request, "partyType", 0);
		Party party = new Party();
		party.setAddress(address);
		party.setDescription(description);
		party.setEndTime(endTime);
		party.setStartTime(startTime);
		party.setUserid(userid);
		// 活动坐标
		Double plon = WebUtil.getDoubleValue(request, "plon", null);
		Double plat = WebUtil.getDoubleValue(request, "plat", null);

		if (null != plon && null != plat) {
			party.setPartyPos(plon, plat);
		}

		if (id < 1) {
			result.put("success", 0);
			JSONResponseHelper.sendJSONResult(response, result, null);
			return;
		}

		PartyResult rs = partyManager.updateParty(party);
		if (rs.isSuccess()) {
			result.put("success", 1);
		} else {
			result.put("success", 0);
			// 是否针对db和solr来处理
			if (rs.getErrorCode() == PartyResult.ERROR_DB_EXCEPTION) {
				logger.error("error_db_exception." + rs.getErrorMsg());
			}
			if (rs.getErrorCode() == PartyResult.ERROR_SOLR) {
				logger.error("error_solr_exception." + rs.getErrorMsg());
			}
		}
		JSONResponseHelper.sendJSONResult(response, result, null);
	}

	@RequestMapping(value = "/mobileapi/party/posupdate")
	public void updatePos(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Integer userid = WebUtil.getIntPara(request, "userid");
		double lon = WebUtil.getDoubleValue(request, "lon");
		double lat = WebUtil.getDoubleValue(request, "lat");
		JSONObject result = new JSONObject();
		Party party = new Party();
		party.setUserid(userid);
		party.setUserPos(lon, lat);

		PartyResult rs = partyManager.updateUserPos(userid, lon, lat);
		if (rs.isSuccess()) {
			result.put("success", 1);
		} else {
			result.put("success", 0);
			// 是否针对db和solr来处理
			if (rs.getErrorCode() == PartyResult.ERROR_DB_EXCEPTION) {
				logger.error("error_db_exception." + rs.getErrorMsg());
			}
			if (rs.getErrorCode() == PartyResult.ERROR_SOLR) {
				logger.error("error_solr_exception." + rs.getErrorMsg());
			}
		}
		JSONResponseHelper.sendJSONResult(response, result, null);
	}

	@RequestMapping(value = "/mobileapi/party/solrquery")
	public void queryPartys(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
	}

	@RequestMapping(value = "/mobileapi/party/dbquery")
	public void queryUserPartys(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String userid = WebUtil.getStringPara(request, "userid");
		JSONObject result = new JSONObject();
		if (userid.isEmpty()) {
			result.put("success", 0);
			result.put("error", "userid错误");
			JSONResponseHelper.sendJSONResult(response, result, null);
			return;
		}
		Integer page = WebUtil.getIntPara(request, "page", 1);
		Integer pageSize = WebUtil.getIntPara(request, "pagesize", 3);
		PartyResult rs = partyManager.getUserPartys(userid, page, pageSize);

		if (rs.isSuccess()) {
			result.put("success", 1);
			result.put("count", rs.getCount());
			result.put("partys", GsonUtil.g.toJson(rs.getPartys()));
		} else {
			result.put("success", 0);
			logger.info("" + rs.getErrorMsg());
		}
		JSONResponseHelper.sendJSONResult(response, result, null);
	}

	@RequestMapping(value = "/mobileapi/party/orderby/time/{start}/{size}")
	public void queryUserPartys(@PathVariable("start") int start, @PathVariable("size") int size,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		List<Party> partys = partyManager.getPartysByTime(start, size);
		JSONObject result = new JSONObject();
		result.put("success", 1);
		GsonBuilder builder = new GsonBuilder();
		builder.setDateFormat(TimeUtils.DEFUALT_DATETIME_FORMAT_STRING);
		Gson gson = builder.create();
		result.put("partys", gson.toJson(partys));
		JSONResponseHelper.sendJSONResult(response, result, null);
	}

	@RequestMapping(value = "/mobileapi/party/query")
	public void query(HttpServletRequest request, HttpServletResponse response) throws Exception {
	}
}
